Overview:
- Reddit is about bringing out the best of the Internet. At reddit, users share some kind of content – a piece of news, a technical article, a digital photograph, a link on YouTube or Sound Cloud…. essentially anything worth sharing in a bulletin board.
- The shared contents are organized into various categories and sub categories as sub-reddits… just like subfolders and subdirectories.
- The fellow users of reddit rate the shared contents with up votes and down votes.
- As a shared content gets more up votes it bubbles upwards and come in the listing of a sub-reddit moving to the front pages and eventually to the main page of reddit.
The Reddit App Development:
A Reddit App is useful in so many ways as designed by the developers.
An app can get the hottest submissions on specific subreddits, can get comments on a specific submission, get the most upvoted threads and so on. To help developers to make use of reddit with their Apps, Reddit offers PRAW- The Python Reddit API Wrapper. Using PRAW applications can be developed using one or more features of reddit. The types of the applications that can be developed using PRAW are Script Application, Web Application and Installed Application.
The script-based application is the simplest one, which does not involve any session based on an access token and a refresh token.
A web application is typically any existing web site, which provides reddit access to its users through an authorization like OAuth.
This article explains how to create a Web Application for Reddit using PRAW – Python Reddit API Wrapper, CherryPy and OAuth.
Developing a Web Application for Reddit using PRAW and CherryPy:
Developing a web application for Reddit involves the following steps:
- Running of a web server, which can be used to execute Python code: To host the web app provided in this article, CherryPy, the python based web framework is used.
- Installation of the PRAW – The Python reddit API wrapper on the computer where the web server is running. PRAW can be installed using pip as given below
pip install praw |
- A page served by the web server to initiate the Authorization process – This page is served from a Python class hosted in CherryPy.
- A page where Reddit will redirect to when authorization is complete. In the example provided this page lists the ten of the hottest submission from the front page of the Reddit.
PRAW – The Python Reddit API Wrapper:
The Python module PRAW has several classes to make use of the various features of reddit. The list of classes include
- Front
- Inbox
- Live
- Multireddit
- Subreddit
- Subreddits
- User
Among the above listed classes of PRAW, the class Reddit forms the primary interface for accessing reddit features. To do anything with reddit an instance of class Reddit is needed first. In case of a web application, a reddit instance is typically obtained by passing the below parameters:
- client_id
- client_secret
- redirect_uri
- user_agent
reddit = praw.Reddit(client_id='VVWOH_b-Oymcgw', client_secret='XaSC6qp68TzlWaniS6F9aeNie2E', redirect_uri='http://localhost:8080', user_agent='testscript by /u/testappreddit', ) |
Through the reddit instance an authorization url can be obtained by passing the required level of access, a state variable and the duration. The access level is a list of strings denoting the various reddit operations for which the authorization is sought. The value of the state is returned with the same value that is passed.
url = reddit.auth.url(redditScopes, stateValue, 'temporary') |
The duration defines the amount of time the access token that is the authorization is valid. If the value, “temporary” is specified then the access token is valid for one hour. At the expiration of one hour or before a new access token has to be acquired using the refresh token. Remember the refresh token is used to a get new access token. If the value, “permanent” is specified the access token is valid indefinitely or till the time it is manually revoked.
Example:
# Example Web Application for Reddit written in Python using PRAW and CherryPy import os.path
# import CherryPy global namespace import cherrypy import io
# import the python reddit api wrapper import random import praw
# Authorise an user to access reddit reddit = praw.Reddit(client_id='xxxxxxxxxxxxxx', client_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxx', redirect_uri='http://localhost:8080', user_agent='testscript by /u/testappreddit', )
stateValue = str(random.randint(512, 1024)) redditScopes = ['read'] url = reddit.auth.url(redditScopes, stateValue, 'permanent')
# class for the authorization page class AuthorizationProcess: @cherrypy.expose def index(self): # Will redirect to Reddit's access grant page if already logged in # else login page first followed by the access grant page raise cherrypy.HTTPRedirect(url)
# Class that serves the home page i.e.,localhost:8080 # In case of authorization complete lists the titles of ten hottest submissions from the # front page of the reddit class AuthorizationForm: @cherrypy.expose def index(self, *args, **kwargs):
content = io.StringIO()
# Home page case - after login if len(kwargs) > 0: content.write('State:') stateRecvd = kwargs['state'] content.write(stateRecvd) content.write('<br>')
content.write('Authorization Token:') bearerToken = kwargs['code'] content.write(bearerToken)
content.write('<br>')
# Get ten hot submissions from the front page of Reddit for submission in reddit.front.hot(limit=10): content.write('<br>') content.write(submission.title)
output = content.getvalue() content.close()
return [bytes(output, 'utf-8')]
# Home page case - before login content.write('<html>') content.write('<head>') content.write('<title>') content.write('For the test application to authorize reddit access') content.write('</title>') content.write('</head>')
content.write('<body>') content.write('<form action="for_reddit_test_auth_user" method="post">') content.write('<h1>A test web application that authorizes a reddit user to access his account</h1>') content.write('User Name') content.write('<input type="text" id="username">') content.write('<br>') content.write('Password') content.write('<input type="password" id="password">') content.write('<br>') content.write('<input type="submit">') content.write('</form>') content.write('</body>')
output = content.getvalue() content.close()
return [bytes(output, 'utf-8')]
conf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__': cherrypy.tree.mount(AuthorizationForm(), '/', config=conf) cherrypy.tree.mount(AuthorizationProcess(), '/for_reddit_test_auth_user', config=conf) cherrypy.engine.start() cherrypy.engine.block() |
Output:
CherryPy listening to serve the web pages for the created reddit test app:
Home page of the test web application for Reddit:
Authroization page for reddit access from the web application:
Ten submissions from the reddit front page displayed in the web application:
The CherryPy console log of the test web apllication for reddit: